package ex.system.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import modules.system.entity.Dictionary;
import modules.system.service.DictionaryService;

import com.guinea.core.tag.DictEntry;
import com.guinea.core.tag.IEntry;
import com.guinea.core.utils.StringUtils;

public class DictionaryServiceEx extends DictionaryService {
	public String getJson(String dictTypes,List dict){
		String[] types = StringUtils.split(dictTypes,',');
		List result = new ArrayList();
		List entryLists = new ArrayList();
		for (int i = 0; i < types.length; i++) {
			String t = types[i];
			if(!StringUtils.isBlank(t)){
				List l = getType(t,dict);
				if(l.size()>0)
					entryLists.add(l);
			}
		}
		if(entryLists.size() == 1)
			result = (List)entryLists.get(0);
		else if(entryLists.size() > 1){
			List children = (List)entryLists.get(entryLists.size()-1);
			for (int i = entryLists.size()-2;i > -1;i--) {
				List parents =  (List) entryLists.get(i);
				children = DictEntry.assembleEntry(parents,children);
			}
			result = children;
		}
		return DictEntry.convertEntryListToJson(result);
	}
	
	public List getType(String type,List dict){
		List result = new ArrayList();
		for (Iterator iter = dict.iterator(); iter.hasNext();) {
			Dictionary d = (Dictionary) iter.next();
			if (d != null && d.getTypeCode() != null
					&& d.getTypeCode().equalsIgnoreCase(type)) {
				result.add(dict2entry(d));
			}
		}
		return result;
	}

	public IEntry dict2entry(Dictionary dictionary){
		DictEntry result = new DictEntry();
		result.setCode(dictionary.getCode());
		result.setName(dictionary.getTitle());
		result.setParentCode(dictionary.getParentCode());
		return result;
	}
}
